var frameId = document.getElementById('mainmenu');
frameId.height = document.documentElement.clientHeight;
frameId.width = document.documentElement.clientWidth;

var myApp = new Framework7({
	root: '#dcontent',
	id: 'cpc.framework7.app',
	name: 'cpc',
	dialog: {
		buttonOk: '确定',
		buttonCancel: '取消'
	}
});

var $$ = Dom7;

function reflashUrl(){
	console.log('flash url');
	var nowurl = getFrameUrl();
	var w = plus.webview.currentWebview();
	ws.beginPullToRefresh();
	console.log('flash url='+nowurl);
//	w.reload(true);
	var timeId24 = setTimeout(function(){
		$('#mainmenu').attr('src', nowurl);	
		w.endPullToRefresh();
		clearTimeout(timeId24);
	},1000);
	
}

function restBtn(){
	var w = plus.webview.currentWebview();
	w.reload(true);
}

function updateUrl() {
	plus.storage.removeItem('frameUrl');
	plus.storage.removeItem('frameYm');
	$('#mainmenu').attr('src', '');
	f7Alert();
}

function changeCount(){
	var url = plus.storage.getItem('frameUrl');
	console.log('change is('+!url+')url = '+url);
	if(!url){
		updateUrl();
	}else{
//		var w = plus.webview.currentWebview();
//		w.reload(true);
		$('#mainmenu').attr('src',url+'&logout=logout');
		console.log('准备开启第二线程:')
		var worker = new Worker('js/cpc2.js');
			
		var da = -1;
		var nu = plus.storage.getItem('frameUrl');
//		console.log('nu is null?='+!nu);
//		if(nu && getFrameUrl()==nu){
//			da = 1;
//		}
			
		var messageData = {
			message: da
		};
		worker.postMessage(messageData);	
			
			
		worker.onmessage = function (e) {
			console.log(JSON.stringify(e));
		    	var data = e.data;
		    	console.log('data:'+data);
		    	if(data == 1){
		    		if(nu && getFrameUrl()==nu){
						console.log('重置，然后是关闭了'); 
		    			restBtn();
		    			var messageData = {
							message: 2
						};
						worker.postMessage(messageData);
						console.log('关闭线程');
		    			worker.terminate();
		    			
					}else{
						console.log('继续发送')
						var messageData = {
							message: 1
						};
						worker.postMessage(messageData);
					}
		    	}else{
		    		console.log('不重置，再发送');
		    		worker.postMessage(messageData);
		    		if(nu && getFrameUrl().indexOf('loginguid=')>0 || getFrameUrl() == nu){
						console.log('重置，然后是关闭了'); 
		    			restBtn();
		    			var messageData = {
							message: 2
						};
						worker.postMessage(messageData);
						console.log('关闭线程');
		    			worker.terminate();
		    			
					}
		    	}
		    	
			}	
			
			
			
	}
}

function gotoSetpage(){
	
	var w = plus.webview.create('pages/setting/setting.html','setting');
	w.show();
	
	
}
var hback = 0;
function goBack() {
		window.frames[0].history.back(-1);	
		hback = -1;
	}

function getFrameUrl(){
	
	var furl = document.getElementById('mainmenu').contentWindow.location.href;
	console.log('furl:'+furl);
	return furl;
	
}

/**
 * @description 获取剪贴板内容 (粘贴)
 */
function getClipbordText() {
    if(!window.plus) return;
    if(mui.os.android) {
        var Context = plus.android.importClass("android.content.Context");
        var main = plus.android.runtimeMainActivity();
        var clip = main.getSystemService(Context.CLIPBOARD_SERVICE);
        return plus.android.invoke(clip, "getText");
    } else {
        var UIPasteboard = plus.ios.importClass("UIPasteboard");
        var generalPasteboard = UIPasteboard.generalPasteboard();
        // 设置/获取文本内容:
        //generalPasteboard.setValueforPasteboardType("testValue", "public.utf8-plain-text");
        //var _val = generalPasteboard.valueForPasteboardType("public.utf8-plain-text");
        // 应用在后台的时候获取剪切版数据被系统限制了，只有在app内才能访问接口
        var _val=generalPasteboard.plusCallMethod({valueForPasteboardType:"public.utf8-plain-text"});
        console.log("ios复制返回的数据是：",_val); 
        return _val || '';
    }
}


var ws=null,isExit=false;
function plusReady() {
	isExit = true;
	var frameUrl = plus.storage.getItem("frameUrl");
	console.log('is ready to start : '+!frameUrl)
	if(!frameUrl) {
		console.log('frameUrl is null,so let do it ');
		updateUrl();
	
	}
	console.log('now mainsrc = '+!$('#mainmenu').attr('src'));
	if(!$('#mainmenu').attr('src')) {
		console.log('frameUrl='+frameUrl);
		$('#mainmenu').attr('src', frameUrl);
		$.ajax({
			type:"get",
			url:frameUrl,
			async:true,
			success : function(data){
				var text = data.split('<title>')[1].split('</title>')[0];
				console.log('title===='+text);
				if(!text){
				}else{
					$('#nvtt-tile').html(text);
				}
			},
			error :function(errMsg){
				console.log('error:'+JSON.stringify(errMsg));
				if(errMsg.responseText.indexOf('Internal Server Error')>0 || errMsg.status == 500){
					changeCount();
					$('#close-btn').trigger('click');
				}
			}
		});
	}
	
	// 隐藏滚动条
	plus.webview.currentWebview().setStyle({
		scrollIndicator: 'none'
	});
	// Android处理返回键
	plus.key.addEventListener('backbutton', function() {
		
		var curl = getFrameUrl();
		var surl = plus.storage.getItem('frameUrl');

		if(curl == surl){
			console.log('backbtn:'+(curl == surl));
			
			ws.canBack(function(e){
				if(e.canBack){
					webview.back(); 
				}else{
					('iOS' == plus.os.name) ? plus.nativeUI.confirm('确认退出？', function(e) {
					if(e.index > 0) {
						plus.runtime.quit();
					}
				}, 'XS', ['取消', '确定']): (confirm('确认退出？') && plus.runtime.quit());
				}
			});
			
		}else{
			console.log('is false an here to back');
			plus.webview.currentWebview().close('auto');
			goBack();
			
		}
		
		
	}, false);
	compatibleAdjust();
	
	
	ws=plus.webview.currentWebview();
	
	ws.drag({direction:'top',moveMode:'followFinger'},{view:ws,moveMode:'follow'},function(e){
		console.log('上滑动事件: '+JSON.stringify(e));
	});
	
	ws.setPullToRefresh({support:true,style:'circle',offset:'45px'}, reflashUrl);


}

function f7Alert() {
	$('#close-btn').trigger('click');	
	
	var txt = getClipbordText();
	
	
	myApp.dialog.prompt('请输入加载地址?', '提示', 
	function(value) {
		myApp.dialog.alert('加载地址： "' + value + '". 将作为默认加载地址', 'tip');
		
		value = setValue(value);
		$('#mainmenu').attr('src', value);
	}, 
	function(value) {
		myApp.dialog.alert('用户取消输入地址，将使APP无法正常使用', '警告');
	}
	,
	txt?txt:'http://pdm.orinko.com.cn/showModApp.jsp?entcode=hfht&modtag=8888'
	);
	
}

function setValue(value){
		var rV = value.split('/');
		rV = value.split(rV[2])[0] + rV[2];
		plus.storage.setItem('frameYm', rV);
		plus.storage.setItem('frameUrl', value);
		plus.storage.setItem('logourUrl',value+'&logout=logout');
		return value;
}

document.addEventListener('plusready', plusReady, false);

// DOMContentLoaded事件处理
var _domReady = false;
document.addEventListener('DOMContentLoaded', function() {
	_domReady = true;
	compatibleAdjust();
}, false);

// 兼容性样式调整
var _adjust = false;

function compatibleAdjust() {
	if(_adjust || !window.plus || !_domReady) {
		return;
	}
	_adjust = true;
	// iOS平台特效
	if('iOS' == plus.os.name) {
		document.getElementById('content').className = 'scontent'; // 使用div的滚动条
		if(navigator.userAgent.indexOf('StreamApp') >= 0) { // 在流应用模式下显示返回按钮
			document.getElementById('back').style.visibility = 'visible';
		}
	}
	// 预创建二级窗口
	//	preateWebviews();
	// 关闭启动界面
	plus.navigator.setStatusBarBackground('#D74B28');
	var timeId = setTimeout(function() {
		plus.navigator.closeSplashscreen();
		clearTimeout(timeId);
	}, 200);
}

/**
 * 点击打开新窗口
 * @param {Object} id	加载的页面地址，也用作窗口标识
 * @param {Object} a	页面动画内心，默认使用全局as设置的值
 * @param {Object} s	是否不显示窗口
 */

var _openw = null;

function clicked(id, a, s) {
	console.log('click to open 扫一扫');
	if(_openw) {
		return;
	}
	console.log('_openw' + _openw);

	a || (a = as);
	_openw = preate[id];
	if(_openw) {
		_openw.showded = true;
		_openw.show(a, null, function() {
			_openw = null; //避免快速点击打开多个页面
		});
	} else {
		//		var wa=plus.nativeUI.showWaiting();
		//		_openw=plus.webview.create(id,id,{scrollIndicator:'none',scalable:false,popGesture:'hide'},{preate:true});//复用二级页面
		_openw = plus.webview.create(id, id, {
			scrollIndicator: 'none',
			scalable: false,
			popGesture: 'close'
		});
		preate[id] = _openw;
		_openw.addEventListener('loaded', function() { //叶面加载完成后才显示
			_openw.showded = true;
			s || _openw.show(a, null, function() {
				_openw = null; //避免快速点击打开多个页面
			});
			s && (_openw = null); //避免s模式下变量无法重置
			//		},10);
		}, false);
		_openw.addEventListener('hide', function() {
			_openw && (_openw.showded = true);
			_openw = null;
		}, false);
		_openw.addEventListener('close', function() { //页面关闭后可再次打开
			_openw = null;
			preate[id] && (preate[id] = null); //兼容窗口的关闭
		}, false);
	}
}

// 预创建二级页面
var preate = {};

function urlload(obj){
			var url = obj.contentWindow.location.href;
			
			var surl;
			if(!isExit){
				surl = $('#mainmenu').attr('src');
			}else{
				surl = plus.storage.getItem('frameUrl');
				var message_ws = messageMail('cpc.js-370,页面地址更改:'+surl);
				plus.messaging.sendMessage(message_ws);
			}
			
			if(hback == -1 && url.indexOf('login') > 0) {
				$('#mainmenu').attr('src', surl);
			}
			
			hback = 0;
			console.log('监控iframe的url变化：' + url);
			
			if(surl == url) {
				$('#back-ion').hide();
			} else {
				$('#back-ion').show();
			}
			
			$.ajax({
				type: "get",
				url: url,
				success: function(data) {
					var text = data.split('<title>')[1].split('</title>')[0];
					console.log('title====' + text);
					if(!text) {} else {
						$('#nvtt-tile').html(text);
						$('#nvtt-tile').text(text);
					}
				},
				error: function(errMsg) {
					console.log('error:' + JSON.stringify(errMsg));
				}
			});
			return url;
		}